﻿using System;

using zijian666.Abstractions;
using zijian666.Convertor.Base;
using zijian666.Core;
using zijian666.ConvertExtensions;

namespace zijian666.Convertor;

/// <summary>
/// <seealso cref="Nullable{T}"/> 可空值类型转换器
/// </summary>
public class NullableConvertor<TValue> : AllowNullConvertor<TValue?>, IConvertor<TValue?>, IFrom<string, TValue?>, IFrom<object, TValue?>
    where TValue : struct
{

    /// <inheritdoc/>
    public override uint Priority { get; } = 1;

    /// <inheritdoc/>
    public ConvertResult<TValue?> From(IConvertContext context, string input)
    {
        if (string.IsNullOrWhiteSpace(input))
        {
            return new(null);
        }
        return From(context, (object)input);
    }

    /// <inheritdoc/>
    public ConvertResult<TValue?> From(IConvertContext context, object input)
    {
        var result = context.Convert<TValue>(input);
        return result.Success ? new(result.Value) : (ConvertResult<TValue?>)result.Exception!;
    }
}
